# -*- coding: utf-8 -*-
import functools

from flask import request, g, current_app, session, abort
from app.utils import api_error
from werkzeug.utils import MultiDict
from flask.ext.login import LoginManager, UserMixin, current_user, login_user, logout_user

from app.constants import mobile_view_spec
from app.utils.html5 import get_user_agent, get_app_version
from app.third_party_api import btapi


def validate_form(form_class):

    def decorator(view_func):
        @functools.wraps(view_func)
        def inner(*args, **kwargs):
            if request.method == 'GET':
                formdata = request.args
            else:
                formdata = request.form if request.form else \
                    MultiDict(request.get_json(force=True))
            form = form_class(formdata=formdata)
            if not form.validate():
                return api_error(49999, form.errors)
            g.form = form
            return view_func(*args, **kwargs)
        return inner

    return decorator


def html5_handle():

    def decorator(view_func):
        @functools.wraps(view_func)
        def inner(*args, **kwargs):
            user_agent = get_user_agent(request)
            app_version = get_app_version(request)
            data = {
                'user_agent': user_agent,
                'mobile_spec': mobile_view_spec[user_agent],
            }
            data.update({'app_version': app_version})
            data.update(request.args)

            g.context = data
            return view_func(*args, **kwargs)
        return inner

    return decorator


def api_login_required(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        from app.models import User

        _session_name = current_app.config['BT_SESSION_COOKIE_NAME']
        sessionid = request.cookies.get(_session_name)
        # if not sessionid:
        #     print 'no sessionid in headers'
        if (not sessionid) or (session.get('last_sessionid') != sessionid):
            logout_user()
            # print 'sessionid changed. logout_user'

        if not current_user.is_authenticated():
            ret, resp = btapi.check_login(sessionid)
            # print 'api_login_required', sessionid, ret
            _user = User()
            if ret['status'] == 0:
                userinfo = ret['data']['user']
                _user.id = userinfo['id']
                login_user(_user)
                session['last_sessionid'] = sessionid
            else:
                abort(401)
        return func(*args, **kwargs)
    return wrapper
